import java.util.ArrayList;
import java.util.List;

public class MovieService implements Loggable {
    private List<Movie> movieList = new ArrayList<>();
    private static final String MOVIE_FILE = "movies.txt"; // 存储影片数据的文件

    // 构造方法：初始化时从文件加载影片数据
    public MovieService() {
        movieList = FileUtil.readMoviesFromFile(MOVIE_FILE);
        // 如果文件为空，初始化示例影片
        if (movieList.isEmpty()) {
            movieList.add(new Movie("M001", "流浪地球", "郭帆", "吴京,屈楚萧", "科幻电影", 125, 8.5));
            movieList.add(new Movie("M002", "满江红", "张艺谋", "沈腾,易烊千玺", "悬疑喜剧", 159, 7.8));
            saveMovies(); // 保存到文件
        }
    }

    // 添加影片
    public void addMovie(Movie movie) {
        movieList.add(movie);
        logOperation("添加影片：" + movie.getName());
    }

    // 按条件查询影片
    public List<Movie> queryMovies(String name, String director, String actor) {
        List<Movie> result = new ArrayList<>();
        for (Movie m : movieList) {
            boolean match = true;
            if (name != null && !m.getName().contains(name)) match = false;
            if (director != null && !m.getDirector().contains(director)) match = false;
            if (actor != null && !m.getActor().contains(actor)) match = false;
            if (match) result.add(m);
        }
        return result;
    }

    // 获取所有影片
    public List<Movie> getAllMovies() {
        return new ArrayList<>(movieList); // 返回副本，避免外部修改
    }

    // 保存影片数据到文件
    public void saveMovies() {
        FileUtil.writeMoviesToFile(movieList, MOVIE_FILE);
    }
}
    